//
//  YRJDestinationViewController.m
//  TravelAroundTheWorld
//
//  Created by dllo on 15/10/22.
//  Copyright (c) 2015年 yanrenjie. All rights reserved.
//

#import "YRJDestinationViewController.h"
#import "YRJTripHeader.h"
#import <SDWebImageOperation.h>

@interface YRJDestinationViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate>
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)NSMutableArray *hotCountryArr;  // 热门国家信息
@property(nonatomic, retain)NSMutableArray *countryArr;     // 国家信息
@property(nonatomic, retain)NSMutableArray *continentArr;   // 洲信息
@property(nonatomic, retain)MBProgressHUD *hud;
@end

NSInteger flag = 0;
@implementation YRJDestinationViewController
- (void)dealloc {
    [_collectionView release];
    [_hotCountryArr release];
    [_countryArr release];
    [_continentArr release];
    [_hud release];
    
    [super dealloc];
}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"目的地";
    self.navigationController.navigationBar.translucent = NO;
    // 修改导航栏的背景颜色
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0 green:190 / 255.0 blue:200 / 255.0 alpha:1];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"Loading...";
    
    // 设置item的大小, item就是tableView的row
    flowLayout.itemSize = CGSizeMake((160.0 / 375) * WIDTH, (220.0 / 667) * HEIGHT);
    // 设置滑动的方向
    // 默认是垂直方向滑动
    //    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 最小行间距
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = (15.0 / 667) * HEIGHT;
    // 给item 设置边框
    flowLayout.sectionInset = UIEdgeInsetsMake(0, (20.0 / 375) * WIDTH, (10.0 / 375) * WIDTH, (20.0 / 667) * HEIGHT);
    // 设置头部的区域范围
    flowLayout.headerReferenceSize = CGSizeMake((20.0 / 375) * WIDTH, (240.0 / 667) * HEIGHT);
    
    
    // 创建collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SWIDTH, SHEIGHT - 113) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    [_collectionView release];
    [flowLayout release];
    // uicollectionView 的背景默认是黑色
    // 签订代理人
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    // collectionView 想要创建cell的花只能使用注册的方式
    [self.collectionView registerClass:[YRJDestinationCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [self.collectionView registerClass:[YRJDestinationCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [self.collectionView registerClass:[YRJDestinationCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView"];
    
    // 它本身带重用的特性, 所以只能注册去使用, 而且注册的方法跟cell的方法不一样

    [self createData];

}


// 从网上请求数据
- (void)createData {
    NSString *strURL = @"http://open.qyer.com/qyer/footprint/continent_list?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&v=1";
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        
        
        
        
        self.continentArr = [YRJContinentModel baseModelByArr:dic[@"data"]];
        NSMutableArray *tempArray1 = [YRJHotCountryModel baseModelByArr:[self.continentArr[0] hot_country]];
        NSMutableArray *tempArray2 = [YRJHotCountryModel baseModelByArr:[self.continentArr[0] country]];
        self.hotCountryArr = [NSMutableArray array];
        
        for (YRJHotCountryModel *tempModel in tempArray1) {
            if (![tempModel.flag isEqualToNumber:@2]) {
                [self.hotCountryArr addObject:tempModel];
            }
        }

        for (YRJHotCountryModel *tempModel in tempArray2) {
            if (![tempModel.flag isEqualToNumber:@2]) {
                [self.hotCountryArr addObject:tempModel];
            }
        }
        
        [self.collectionView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

// UICollectionReusableView 的方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {
        YRJDestinationCollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        // 将7大洲的按钮放到数组中, 方便创建
        NSArray *array = @[reusableView.AsiaButton, reusableView.EuropeButton, reusableView.NorthAmericaButton, reusableView.SouthAmericaButton, reusableView.OceaniaButton, reusableView.AfricaButton, reusableView.AntarcticaButton];
        
        for (NSInteger i = 0; i < array.count; i++) {
            [(UIButton *)array[i] setTitle:[self.continentArr[i] cnname] forState:UIControlStateNormal];
            [(UIButton *)array[i] addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
            [(UIButton *)array[i] setTag:(1000 + i)];
        }
        
        if (indexPath.section == 0) {
            [reusableView.mapImageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.gifmania.tw/Gifs-Duixiang/Gifs-Educational-Material/Gifs-World-map/World-map-85896.gif"] placeholderImage:[UIImage imageNamed:@"worldMap.png"]];
            // 打开用户交互
            reusableView.mapImageView.userInteractionEnabled = YES;
            // 给图片添加一个轻点手势
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            //把手势加到指定的视图上
            [reusableView.mapImageView addGestureRecognizer:tap];
            [tap release];
            tap.numberOfTapsRequired = 1;  // 需要点击的次数
            reusableView.titleNameLabel.text = [self.continentArr[flag] cnname];
        } else {
            reusableView.titleNameLabel.text = @"其他目的地";
        }
        return reusableView;
    }
    return nil;
}


#pragma mark 地图上的洲名按钮实现方法
- (void)clickAction:(UIButton *)button {
    NSInteger buttonIndex = [button tag] - 1000l;
    flag = buttonIndex;
    self.hotCountryArr = [YRJHotCountryModel baseModelByArr:[self.continentArr[buttonIndex] hot_country]];
    self.countryArr = [YRJCountryModel baseModelByArr:[self.continentArr[buttonIndex] country]];
    [self.collectionView reloadData];
}


#pragma mark CollectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return self.hotCountryArr.count;
    } else {
        return self.countryArr.count;
    }
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        YRJDestinationCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
        if (self.hotCountryArr.count != 0) {
            cell.cnnameLabel.text = [self.hotCountryArr[indexPath.row] cnname];
            cell.ennameLabel.text = [self.hotCountryArr[indexPath.row] enname];
            cell.photoImageView.userInteractionEnabled = YES;
            [cell.photoImageView sd_setImageWithURL:[NSURL URLWithString:[self.hotCountryArr[indexPath.row] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
//            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
//            //把手势加到指定的视图上
//            [cell.photoImageView addGestureRecognizer:tap];
//            [tap release];
            
//            tap.numberOfTapsRequired = 1;  // 需要点击的次数
        }
        return cell;
    } else {
        YRJDestinationCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
        if (self.countryArr.count != 0) {
            cell.cnnameLabel.text = [self.countryArr[indexPath.row] cnname];
            cell.ennameLabel.text = [self.countryArr[indexPath.row] enname];
            cell.photoImageView.userInteractionEnabled = YES;
            [cell.photoImageView sd_setImageWithURL:[NSURL URLWithString:[self.countryArr[indexPath.row] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
//            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
//            //把手势加到指定的视图上
//            [cell.photoImageView addGestureRecognizer:tap];
//            [tap release];
//            tap.numberOfTapsRequired = 1;  // 需要点击的次数
        }
        return cell;
    }
}


// 轻点触发实现方法
// 点击之后触发的方法
- (void)tapAction:(UITapGestureRecognizer *)tap {
    YRJCountryDetailViewController *countryDetailVC = [[YRJCountryDetailViewController alloc] init];
//    [self.navigationController pushViewController:countryDetailVC animated:YES];
//    NSLog(@"%ld", tap.view.tag);
    [countryDetailVC release];
}


- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}


#pragma mark collectionView的cell的点击实现方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    YRJCountryDetailViewController *countryDetailVC = [[YRJCountryDetailViewController alloc] init];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:countryDetailVC animated:YES];
    if (indexPath.section == 0) {
        countryDetailVC.string = [[self.hotCountryArr[indexPath.row] id] stringValue];
        countryDetailVC.countryName = [self.hotCountryArr[indexPath.row] cnname];
        countryDetailVC.hotCountrymodel = self.hotCountryArr[indexPath.row];
    } else if (indexPath.section == 1) {
        countryDetailVC.string = [[self.countryArr[indexPath.row] id] stringValue];
        countryDetailVC.countryName = [self.countryArr[indexPath.row] cnname];
        countryDetailVC.countryModel = self.countryArr[indexPath.row];
    }
    [countryDetailVC release];
}


- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
    animated = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
